from django.db import models
import ast
from django.db.models import FileField
from django.forms import forms

class ListField(models.TextField):
	description = 'just a listfield'

	def __init__(self,*args,**kwargs):
		super(ListField,self).__init__(*args,**kwargs)

	def from_db_value(self,value,expression,conn,cotext):
		print 'from_db_value'
		if not value:
			value = []
		if isinstance(value,list):
			return value
		print 'value type:{}'.format(type(value))
		return ast.literal_eval(value)

	def get_prep_value(self, value):
		print 'get_prep_value'
		if not value:
			return value
		print 'value type:{}'.format(type(value))
		return str(value)

class ContextTypeRestrictedFileField(FileField):
	def __init__(self,content_type=None,max_upload_size=None,**kwargs):
		self.content_type = content_type
		self.max_upload_size = max_upload_size
		super(ContextTypeRestrictedFileField,self).__init__(**kwargs)

	def clean(self,*args,**kwargs):
		data = super(ContextTypeRestrictedFileField,self).clean(*args,**kwargs)
		file = data.file
		try:
			type = file.content_type
			if type != self.content_type:
				raise forms.ValidationError('pelease upload right filetype')
		except AttributeError:
			print 'error'
			pass
		return data